from queue import Queue
from DrissionPage._base.driver import Driver
from time import perf_counter, sleep
from curl_cffi import requests
from curl_cffi.requests import AsyncSession
import base64
import traceback


class Set_Proxies_V1:
    def __init__(self, page, proxies=None, proxy=None, proxy_auth=None) -> None:
        self._page = page
        self._address = page.address
        self._target_id = page._target_id
        self._driver = None
        self.proxies = proxies
        self.proxy = proxy
        self.proxy_auth = proxy_auth
        self.start()

    def start(self):
        self._driver = Driver(self._target_id, "page", self._address)
        self._driver.run("Fetch.enable")
        self._set_callback()

    def _set_callback(self):
        self._driver.set_callback("Fetch.requestPaused", None)
        self._driver.set_callback("Fetch.requestPaused", self.requestPaused)

    def Requests(self, kwargs):
        try:
            url = kwargs.get("request").get("url")
            headers = kwargs.get("request").get("headers")
            method = kwargs.get("request").get("method")
            postData = kwargs.get("request").get("postData")
            res = requests.request(
                method=method,
                url=url,
                headers=headers,
                data=postData,
                proxies=self.proxies,
                proxy=self.proxy,
                proxy_auth=self.proxy_auth,
            )
            _headers = self.Format_Headers(res.headers)
            _body = self.Format_Body(res.content)
            _code = res.status_code
            return True, _headers, _body, _code
        except:
            print(kwargs)
            error_message = traceback.format_exc()
            print(error_message)
            return False, None, None, None

    def Format_Body(self, body):
        base64_body = base64.b64encode(body).decode("utf-8")
        return base64_body

    def Format_Headers(self, headers):
        _headers = []
        for header in headers:
            _headers.append({"name": header, "value": headers.get(header)})
        return _headers

    def requestPaused(self, **kwargs):
        _bool, _headers, _body, _code = self.Requests(kwargs)
        if _bool == True:
            self._driver.run(
                "Fetch.fulfillRequest",
                requestId=kwargs.get("requestId"),
                responseCode=_code,
                responseHeaders=_headers,
                body=_body,
            )
        else:
            self._driver.run(
                "Fetch.failRequest",
                requestId=kwargs.get("requestId"),
                errorReason="Failed",
            )
